<?php

namespace App\Repositories;

use App\Models\Position;
use Illuminate\Database\Eloquent\Model;

/**
 * 用户模块Repository
 *
 * Date: 22/03/2018
 * @author George
 * @package App\Repositories
 */
class PositionRepository extends BaseRepository
{
	/**
	 * 定义模型类
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @return mixed|string
	 */
	public function model()
	{
		return Position::class;
	}

	/**
	 * 创建模型资源
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param array $attributes
	 * @return Position
	 * @throws \Throwable
	 */
	public function store(array $attributes = [])
	{
		if (count($attributes) < 0) {
			throw new GeneralException('未提供任何属性', 400);
		}

		$model = $this->serialization($attributes);
		$model->saveOrFail();
		return $model;
	}

	/**
	 * 更新模型属性
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param Position $position
	 * @param array $attributes
	 * @return Position
	 * @throws GeneralException
	 */
	public function update(Position $position, array $attributes = [])
	{
		try {
			$position->update($attributes);
			return $position;
		} catch (Exception $exception) {
			throw new GeneralException('未知错误导致更新失败', 500);
		}
	}

	/**
	 * 同步岗位权限
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param Position $position
	 * @param array $permissions
	 * @return Position|\Illuminate\Http\JsonResponse
	 */
	public function syncPermissions(Position $position, array $permissions = [])
	{
		try {
			$position->permissions()->sync($permissions);
			return $position;
		} catch (Exception $e) {
			return internalError();
		}
	}

	/**
	 * 根据公司ID获取岗位
	 *
	 * Date: 24/04/2018
	 * @author George
	 * @param $company
	 * @param $name
	 * @return \Illuminate\Database\Eloquent\Collection|static[]
	 */
	public function getByCompany($company, $name = false)
	{
		$this->unsetClauses();

		$this->newQuery()->eagerLoad();

		$this->query->where('company_id', $company);

		if ($name) {
			$this->query->where('name', 'like', "%{$name}%");
		}
		return $this->query->get();
	}

	/**
	 * 根据部门ID获取岗位信息
	 *
	 * Date: 24/04/2018
	 * @author George
	 * @param $department_id
	 * @param bool $name
	 * @return \Illuminate\Database\Eloquent\Collection|static[]
	 */
	public function getByDepartment($department_id, $name = false)
	{
		$this->unsetClauses();

		$this->newQuery()->eagerLoad();

		$this->query->where('department_id', $department_id);

		if ($name) {
			$this->query->where('name', 'like', "%{$name}%");
		}
		return $this->query->get();
	}

	/**
	 * 序列化属性为模型实例
	 *
	 * Date: 22/03/2018
	 * @author George
	 * @param array $attributes
	 * @return Position|Model
	 */
	protected function serialization(array $attributes)
	{
		foreach ($attributes as $key => $value) {
			$this->model->{$key} = $value;
		}
		return $this->model;
	}
}
